package com.beiing.tianshuai.tianshuai.mine.ui;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.VersionInfoBean;
import com.beiing.tianshuai.tianshuai.network.DataManager;
import com.beiing.tianshuai.tianshuai.service.UpdateAppService;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.CheckVersionDialog;
import com.beiing.tianshuai.tianshuai.widget.DownLoadProgressDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.MessageFormat;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

/**
 * about app:
 * include introduction about the app, checking new version of app and so on.
 * Created by magikliu on 2017/10/18.
 */

public class AboutAppActivity extends BaseActivity {

    private String versionNameNow;
    private int versionCodeNow;
    private DownLoadProgressDialog mProgressDialog;
    private String mAppName;
    private int mFileLength;
    private File mFile;

    @BindView(R.id.toolbar_iv_back)
    ImageView toolbarIvBack;
    @BindView(R.id.toolbar_tv_title)
    TextView toolbarTvTitle;
    @BindView(R.id.toolbar_rv_back)
    RelativeLayout toolbarRvBack;
    @BindView(R.id.tv_current_version)
    TextView tvCurrentVersion;
    @BindView(R.id.tv_check_version)
    TextView tvCheckVersion;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_about_app;
    }

    @Override
    protected void init() {
        initToolbar();
        initListener();
        initData();
        initDialog();
    }

    private void initData() {
        try {
            versionNameNow = mContext.getPackageManager().getPackageInfo("com.beiing.tianshuai.tianshuai", 0).versionName;
            versionCodeNow = mContext.getPackageManager().getPackageInfo("com.beiing.tianshuai.tianshuai", 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        tvCurrentVersion.setText(MessageFormat.format("当前版本V{0}", versionNameNow));
    }

    private void initToolbar() {
        toolbarTvTitle.setText("关于天率校园");
        toolbarIvBack.setVisibility(View.VISIBLE);
    }

    private void initListener() {
        toolbarIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        tvCheckVersion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkNewVersion();
            }
        });
    }

    private void checkNewVersion() {
        DisposableObserver<VersionInfoBean> observer = new DisposableObserver<VersionInfoBean>() {
            @Override
            public void onNext(@NonNull VersionInfoBean versionInfoBean) {
                onCheckResult(versionInfoBean);
            }

            @Override
            public void onError(@NonNull Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };
        DataManager.getVersionInfo()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    private void onCheckResult(VersionInfoBean versionInfoBean) {
        VersionInfoBean.DataBean.NumberBean versionInfo = versionInfoBean.getData().getNumber();
        String versionName = versionInfo.getVersionname();
        String description = versionInfo.getDescription();
        mAppName = versionInfo.getApk();
        if (Integer.parseInt(versionInfo.getVersioncode()) > versionCodeNow) {
            //有待更新新版本
            CheckVersionDialog dialog = new CheckVersionDialog(mContext, R.style.dialog, new CheckVersionDialog.OnCloseListener() {
                @Override
                public void onClick(Dialog dialog, boolean confirm, int id) {
                    if (confirm) {
                        switch (id) {
                            case R.id.btn_update_now:
                                mProgressDialog.setCancelable(false);
                                mProgressDialog.setCanceledOnTouchOutside(false);
                                mProgressDialog.show();
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        // 开始下载
                                        downloadFile();
                                    }
                                }).start();
                                break;
                            case R.id.btn_update_background:
                                showShortText("已转到后台下载最新版APK");
                                Intent intent = new Intent(mContext, UpdateAppService.class);
                                intent.putExtra("app_name", mAppName);
                                intent.putExtra("url", HttpRequestConstant.REQUEST_DOWNLOAD_APK + mAppName);
                                mContext.startService(intent);
                                break;
                            default:
                                break;
                        }
                    }
                    dialog.dismiss();
                }
            }).setContent(description).setVersionName("V" + versionName);
            dialog.show();
        } else {
            showShortText("没有检测到新版本");
        }
    }

    private void downloadFile() {
        try {
            URL url = new URL(HttpRequestConstant.REQUEST_DOWNLOAD_APK + mAppName);
            LogUtils.i(HttpRequestConstant.REQUEST_DOWNLOAD_APK + mAppName, "apkURL");
            try {
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                InputStream inputStream = conn.getInputStream();
                mFileLength = conn.getContentLength();
                mProgressDialog.setMax(mFileLength);
                String dirPath = Environment.getExternalStorageDirectory() + "/TianShuai/天率校园/";
                File apkDir = new File(dirPath);
                if (!apkDir.exists()) {
                    if (apkDir.mkdirs()) {
                        LogUtils.i("创建路径 “/TianShuai/天率校园/” 成功", "make dir");
                    } else {
                        LogUtils.e("创建路径 “/TianShuai/天率校园/” 失败", "make dir");
                    }
                }
                String path = dirPath + mAppName;
                mFile = new File(path);
                FileOutputStream fileOutputStream = new FileOutputStream(mFile);
                int length;
                int progress = 0;
                byte[] bytes = new byte[1024];
                while ((length = inputStream.read(bytes)) != -1) {
                    fileOutputStream.write(bytes, 0, length);
                    progress += length;
                    Message msgUpdateProgress = new Message();
                    msgUpdateProgress.what = 100;
                    msgUpdateProgress.obj = progress;
                    mHandler.sendMessage(msgUpdateProgress);
                }
                inputStream.close();
                fileOutputStream.close();
                fileOutputStream.flush();
                Message msgDownloadFinish = new Message();
                msgDownloadFinish.what = 200;
                mHandler.sendMessage(msgDownloadFinish);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                //更新dialog进度
                case 100:
                    int count = (int) message.obj;
                    mProgressDialog.setProgress(count);
                    float price = (float) count / (float) mFileLength * 100;
                    //构造方法的字符格式这里如果小数不足2位,会以0补足.
                    DecimalFormat decimalFormat = new DecimalFormat(".00");
                    //format 返回的是字符串
                    String p = decimalFormat.format(price);
                    mProgressDialog.setPercent("下载进度" + p + "%");
                    break;
                //下载完成
                case 200:
                    if (mProgressDialog.isShowing()) {
                        mProgressDialog.dismiss();
                    }
                    //判读版本是否在7.0以上
                    if (Build.VERSION.SDK_INT >= 24) {
                        updateMoreThan7();
                    } else {
                        updateUnderAndroid7();
                    }
                    break;
                default:
                    break;
            }
            return false;
        }
    });

    private void initDialog() {
        mProgressDialog = new DownLoadProgressDialog(mContext, R.style.dialog);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setCancelable(false);
    }

    /**
     * 安装程序
     */
    private void updateUnderAndroid7() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(Environment
                        .getExternalStorageDirectory(), mAppName)),
                "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    private void updateMoreThan7() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri apkURI = FileProvider.getUriForFile(mContext, "com.beiing.tianshuai.fileprovider", mFile);
        intent.setDataAndType(apkURI, "application/vnd.android.package-archive");
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //添加这一句表示对目标应用临时授权该Uri所代表的文件
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(intent);
    }

}
